<template>
    <div>
        <search-form :areaMuti="false" :autoDefault="false" @search="getDataList"></search-form>
        <h1>年度综合评价分析-趋势图</h1>
        <div id="main" style="height: 500px;width: 100%;"></div>
    </div>
</template>
<script>
import * as echarts from 'echarts'
import SearchForm from '@/components/search-form'

export default {
    components: {SearchForm},
    data() {
        return {
            title: {},
            legendData: [],
            indicatorData: [],
            seriesData: [],
            sourceData: null,
            chartData: {
                years: [],
                countries: [

                ]
            },
            myChart: null
        }
    },
    mounted() {
        this.init()
        // 基于准备好的dom，初始化echarts实例

    },

    methods: {
        init() {

            this.getDataList({

            })
        },
        getDataList(params, done) {
            console.log('🚀 ~ params', params)
            this.dataListLoading = true
            this.$http({
                url: this.$http.adornUrl('/admin/analysis/bseResultCountryYear'),
                method: 'post',
                params: this.$http.adornParams(
                    {
                        ...params,
                        countryId: params.indexArea
                    }
                )
            }).then(({data}) => {

                console.info('--------------')
                console.info(data)
                this.dataListLoading = false
                this.sourceData = data;
                console.log("🚀 ~ this.sourceData", this.sourceData)
                const yearsSet = []
                this.sourceData.forEach(item => {
                    if(!yearsSet.includes(item.bseYear)){
                        yearsSet.push(item.bseYear)
                    }
                })
                // 排序年份（按数字大小排序）
                this.chartData.years = Array.from(yearsSet)
                    .sort((a, b) => Number(a) - Number(b))

                // 步骤2：按国家分组
                const countryMap = {}
                this.sourceData.forEach(item => {
                    const country = item.conuntryName
                    if (!countryMap[country]) {
                        // 初始化每个国家的分数数组（全部填充0）
                        countryMap[country] = {
                            name: country,
                            scores: new Array(this.chartData.years.length).fill(0)
                        }
                    }

                    // 找到年份对应的索引
                    const yearIndex = this.chartData.years.indexOf(String(item.bseYear))
                    console.log("🚀 ~ yearIndex", yearIndex)
                    // 填充分数到对应位置
                    if (yearIndex !== -1) {
                        countryMap[country].scores[yearIndex] = item.sumScore
                    }
                })
                // 步骤3：转换为数组格式
                this.chartData.countries = Object.values(countryMap)
                console.log("🚀 ~ this.chartData", this.chartData)
                let max = 0
                this.chartData.countries.forEach(country => {
                    country.scores.forEach(score => {
                        if (score > max) {
                            max = score
                        }
                    })
                })

                this.$nextTick(() => {
                    // let myChart = echarts.init(document.getElementById("main"))

                    let chartDom = document.getElementById("main");
                    if (this.myChart) {
                        this.myChart.dispose(); // 销毁旧实例
                    }
                    this.myChart = echarts.init(chartDom); // 创建新实例
                    // 绘制图表

                    this.myChart.setOption({
                        title: {
                            text: '',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
                            data: this.chartData.countries.map(item => item.name),
                            top: 10
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: this.chartData.years,
                            axisLabel: {
                                fontSize: 14
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '评分',
                            min: 0,
                            max: max,
                            axisLabel: {
                              formatter: function (value) {
                                return value.toFixed(2);
                              }
                            }
                        },
                        series: this.chartData.countries.map(country => ({
                            name: country.name,
                            type: 'bar',
                            data: country.scores,
                            barWidth: 20,
                            itemStyle: {
                                borderRadius: [5, 5, 0, 0]
                            }
                        }))
                    })
                })

                if (done) {
                    done()
                }
            })
        }

    },
}
</script>
<style>
h1 {
    text-align: center;
    color: gray;
}
</style>
